package com.suoluo.zenadmin.controllers.admin.weibo;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

import weibo4j.Timeline;
import weibo4j.Weibo;
import weibo4j.http.ImageItem;
import weibo4j.model.WeiboException;

import com.suoluo.zenadmin.service.ServiceException;
import com.suoluo.zenadmin.service.account.AccountService;
import com.suoluo.zenadmin.vo.account.OpenAccountVO;
import com.suoluo.zenadmin.vo.weibo.WeiBoVO;

@Path("/")
public class WeiBoController {

	@Resource(name="accountService")
	private AccountService accountService;
	
	private static Log logger = LogFactory.getLog(WeiBoController.class);
	@Get("vsend")
	public String toSendWeibo()
	{
		return "sendSinaWeiBo";
	}
	@Post("send")
	public String sendWeiBo(Invocation invo,WeiBoVO weiboVO)
	{
		
		MultipartFile[] images = weiboVO.getMfile();
		List<MultipartFile> list = new ArrayList<MultipartFile>();
		list = Arrays.asList(images);
		
		//ModelAndView mv = toSendWeiBoView(request,response);
		
		try {
			String userScreen = weiboVO.getUserScreen();
			String content = weiboVO.getWeiboDesc();
			// 查询用户accestorken
			OpenAccountVO openAccount = accountService.findOpenAccountByName(userScreen);
			
			Timeline tl = new Timeline();
			Weibo weibo = new Weibo();
			if(openAccount != null)
			{
				weibo.setToken(openAccount.getToken());
				byte [] plusImgBuf = merge(list, "jpg");
				ImageItem pic = new ImageItem("pic", plusImgBuf);
				content = java.net.URLEncoder.encode(content, "utf-8");
				
				tl.UploadStatus(weibo, content,pic);
				invo.addModel("res","微博已发成功！");
			}else{
				invo.addModel("res","用户不存在");
			}
			
			
		}catch(ServiceException serviceException)
		{
			logger.error("",serviceException);
			invo.addModel("res",serviceException.getMessage());
		}
		catch (UnsupportedEncodingException e1) {
			logger.error("Fail to send sina WeiBo",e1);
			invo.addModel("res",e1.getMessage());
		}catch (WeiboException e) {
			logger.error("fail to send weibo,errorCode="+ e.getErrorCode()+",errorMsg="+e.getError(),e);
			invo.addModel("res","发微博失败！");
		}
		
		//返回发微博界面
		return "sendSinaWeiBo";
	}
	/**
	 * Java拼接多张图片
	 * 
	 * @param pics 通过页面上传的文件流集合
	 * @param type 指定生成图片的格式
	 * @param dst_pic 指定图片保存路径
	 * @return 字节数组的文件
	 */
	public static byte[] merge(List<MultipartFile> pics, String type) {

//		int len = pics.size();
		if (pics == null || pics.isEmpty()) {
			return null;
		}
		int imgSize = pics.size();
		List<BufferedImage> imgBufs = new ArrayList<BufferedImage>(imgSize);
		int plusImgWidth = 0;
		int plusImgHeight = 0;
		for (MultipartFile file : pics) {
			
			try {
				if (file.getSize() == 0){
					continue;
				}
				BufferedImage imgBuf  = ImageIO.read(file.getInputStream());
				imgBufs.add(imgBuf);
				int width = imgBuf.getWidth();
				if (width > plusImgWidth){
					plusImgWidth = width;
				}
				plusImgHeight += imgBuf.getHeight();
			} catch (Exception e) {
				throw new ServiceException("",file.getOriginalFilename()+":"+e.getMessage());
			}
			
		}
		int imgGap = 10;
		// 创建新图 写像素  creat a new picture and insert into all of the px 
		//凭借的图片，每张图片之间加上10px的间距
		plusImgHeight = plusImgHeight + (imgSize -1) * imgGap;
		BufferedImage plusImg = new BufferedImage(plusImgWidth, plusImgHeight, BufferedImage.TYPE_INT_RGB);
		// 设置背景 set the background color

		Graphics g = plusImg.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0,0,plusImgWidth,plusImgHeight);
		
		int heightTemp = 0;
		for(BufferedImage imgBuf : imgBufs){
			// 绘制图片 draw the picture
			int imgHeight = imgBuf.getHeight();
			int imgWidth = imgBuf.getWidth();
			int [] rgbAry = imgBuf.getRGB(0, 0, imgWidth, imgHeight, new int[imgWidth * imgHeight], 0, imgWidth);
			plusImg.setRGB(0, heightTemp, imgWidth, imgHeight, rgbAry, 0, imgWidth);
			heightTemp = heightTemp + imgHeight + imgGap;

		}
		try {
			ByteArrayOutputStream plusImgBuf = new ByteArrayOutputStream();
			ImageIO.write(plusImg, type, plusImgBuf);
			return plusImgBuf.toByteArray();
		} catch (Exception e) {
			throw new ServiceException("","拼接错误:"+e.getMessage());
		}
	}
}
